package com.object.oriented.exam.system7.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.object.oriented.exam.system1.dao.KnowledgeMapping;
import com.object.oriented.exam.system1.dao.ProblemMapping;
import com.object.oriented.exam.system1.entity.Knowledge;
import com.object.oriented.exam.system1.entity.Problem;
import com.object.oriented.exam.system2.dao.ProblemPropertyMapping;
import com.object.oriented.exam.system2.entity.ProblemProperty;
import com.object.oriented.exam.system5.entity.Answer;
import com.object.oriented.exam.system5.mapper.AnswerMapper;
import com.object.oriented.exam.system7.enetity.ErrorProblem;
import com.object.oriented.exam.system7.service.AnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class AnalysisServiceImpl implements AnalysisService {

    @Autowired
    private AnswerMapper answerMapper;

    @Autowired
    private ProblemMapping problemMapping;

    @Autowired
    private KnowledgeMapping knowledgeMapping;

    @Autowired
    private ProblemPropertyMapping problemPropertyMapping;

    @Override
    public List<ErrorProblem> getErrorProblem(Long studentId, Long examId) {
        //寻找要拼装的所有数据

        //answer
        QueryWrapper<Answer> aWrapper = new QueryWrapper<>();
        aWrapper.eq("exam_id",examId);
        aWrapper.eq("student_id",studentId);
        aWrapper.eq("result",1);
        List<Answer> errorAnswers = answerMapper.selectList(aWrapper);

        //problem
        List<Long> errorProblemIds = errorAnswers.stream().map(Answer::getQuestionId).collect(Collectors.toList());
        List<Problem> problems = problemMapping.selectBatchIds(errorProblemIds);
        Map<Long,Problem> pMap = problems.stream().collect(Collectors.toMap(Problem::getId,p -> p));

        //knowledge
        Set<Long> errorKnowledgeIds = problems.stream().map(Problem::getKnowledgeId).collect(Collectors.toSet());
        Map<Long,Knowledge> kMap = knowledgeMapping.selectBatchIds(errorKnowledgeIds).stream().collect(Collectors.toMap(Knowledge::getId,k->k));

        //problemProperty
        QueryWrapper<ProblemProperty> ppWrapper = new QueryWrapper<>();
        ppWrapper.in("question_id",errorProblemIds);
        Map<Long,ProblemProperty> ppMap = problemPropertyMapping.selectList(ppWrapper).stream().collect(Collectors.toMap(ProblemProperty::getQuestionId,pp -> pp));


        List<ErrorProblem> result = new ArrayList<>();

        for (Answer ea : errorAnswers) {
            //找到对应的题目
            result.add(new ErrorProblem(pMap.get(ea.getQuestionId()),
                    ea,
                    ppMap.get(ea.getQuestionId()),
                    kMap.get(ea.getQuestionId())));

        }
        return result;
    }
}
